package com.example.xiaoxueqixiangmu.jiemian;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.xiaoxueqixiangmu.R;
import com.example.xiaoxueqixiangmu.bean.Passengers;
import com.example.xiaoxueqixiangmu.utils.Constant;
import com.example.xiaoxueqixiangmu.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyContact extends AppCompatActivity {
    private static final String TAG="MyContact";
    private ListView listView;
    private SimpleAdapter simpleAdapter;
    private List<HashMap<String,Object>> dataItem;
    private ProgressDialog progressDialog;
    public static MyContact myContact;

    private final int REQUEST_CODE=101;
    private int pos;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            if (progressDialog!=null){
                progressDialog.dismiss();
            }
            dataItem.clear();
            switch (msg.what){
                case 1:
                    dataItem.clear();
                    Passengers [] passengers=(Passengers[]) msg.obj;
                    for (Passengers passenger:passengers){
                        HashMap<String,Object> showitem=new HashMap<String, Object>();
                        showitem.put("Names",passenger.getName());
                        showitem.put("posts",passenger.getType());
                        showitem.put("sf",passenger.getIdType());
                        showitem.put("ids",passenger.getId());
                        showitem.put("dh","电话:");
                        showitem.put("tels",passenger.getTel());
                        showitem.put("icons",R.mipmap.forward_25);
                        dataItem.add(showitem);
                    }
                    simpleAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    Toast.makeText(MyContact.this,"网络异常，请检查！",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        try {
            Class<?>menuClass=Class.forName("com.android.internal.view.menu.MenuBuilder");
            Method menuMethod=menuClass.getDeclaredMethod("setOptionalIconsVisible",boolean.class);
            menuMethod.setAccessible(true);
            menuMethod.invoke(menu,true);
        }catch (Exception e){
            e.printStackTrace();
        }
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.contact_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_contact);

        listView=(ListView)findViewById(R.id.listView);
        dataItem=new ArrayList<HashMap<String, Object>>();

        simpleAdapter=new SimpleAdapter(this,dataItem,R.layout.mylist2,new String[]{"Names","posts","sf","ids","dh"
                ,"tels","icons"},new int[]{R.id.tx_name,R.id.tx_post,R.id.tx_sf,R.id.tx_id,R.id.tx_dh,R.id.tx_tel,R.id.tx_icon});
        listView.setAdapter(simpleAdapter);

        //添加返回导航
        ActionBar actionBar=getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);


        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(MyContact.this,editMycontact.class);
                intent.putExtra("row",(Serializable)dataItem.get(position));
                pos=position;
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onResume(){
        super.onResume();
        if (!NetUtils.check(MyContact.this)){
            Toast.makeText(MyContact.this,"网络异常！",Toast.LENGTH_SHORT).show();
            return;
        }
        //弹出对话框
        progressDialog=ProgressDialog.show(MyContact.this,null,"正在加载中...",false,true);

        new Thread(){
            @Override
            public void run() {
                String result=null;
                Message msg=Message.obtain();
                //读取已经存好的sessionId
                SharedPreferences preferences=MyContact.this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
                String value=preferences.getString("cookie","");
                Log.d(TAG,"读取的sessionId:"+value);

                try {
                    OkHttpClient client=new OkHttpClient();
                    Request request=new Request.Builder()
                            .addHeader("Cookie",value)
                            .url(Constant.Host+"/otn/PassengerList")
                            .build();
                    Response response=client.newCall(request).execute();
                    result=response.body().string();
                    Log.d(TAG,"获取的服务器数据："+result);
                    //解析json数据
                    Gson gson=new GsonBuilder().create();
                    Passengers[] passengers=gson.fromJson(result,Passengers[].class);
                    msg.what=1;
                    msg.obj=passengers;
                }catch (IOException e){
                    e.printStackTrace();
                }
                handler.sendMessage(msg);
            }
        }.start();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.add:
                Intent intent2=new Intent(MyContact.this,MyContact_add.class);
                startActivity(intent2);
                Toast.makeText(MyContact.this,"点击了添加",Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}